package com.incross.dawin.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageButton;

public class BKImageDownloaderTask extends AsyncTask<String, Void, Boolean> {
	public final static int BUFFER_SIZE = 10240;
	private static final int HTTP_REQUEST_TIMEOUT = 500;
	
	public String url;
	public String filename;
	private WeakReference<ImageButton> buttonReference;
	private String mCachePath;
	private ImageButton mButton;
	private boolean mIsShowDirectly;
	
	private boolean mIsCacheDownload = true;
	
	private ArrayList<String> mBitmapUrlArray;
	private ArrayList<Bitmap> mBitmapResultArray;
	
	private String TEMP_CACHE_PATH = "";
	private String TEMP_FILE_NAME = "";
	
	private OnDownloadFinishListener mDownloadFinishListener;
	private OnBitmapDownFinishListener mBitmapDownloadFinishListenr;
	
	public interface OnDownloadFinishListener {
		public abstract void onDownloadFinished(boolean result, String requestedUrl);
	}
	
	public interface OnBitmapDownFinishListener {
		public abstract void onBitmapDownloadFinished(boolean result, ArrayList<Bitmap> bitmapArray);
	}
	
	public BKImageDownloaderTask(String url, String filename, String cachePath) {
		this.url = url;
		this.filename = filename;
		mCachePath = cachePath;
		mIsCacheDownload = true;
	}
	
	public BKImageDownloaderTask(Context context, ArrayList<String> bitmapUrlArray) {
		TEMP_CACHE_PATH = context.getCacheDir().getAbsolutePath() + "/temp/";
		this.mBitmapUrlArray = bitmapUrlArray;
		mIsCacheDownload = false;
	}
	
	public void downloadImage(ImageButton button, boolean isShowDirectly) {
		mButton = button;
		this.buttonReference = new WeakReference<ImageButton>(mButton);
		mIsShowDirectly = isShowDirectly;
		execute();
	}
	
	public void downloadImage() {
		execute();
	}
	
	public void setOnDownloadFinishListener(OnDownloadFinishListener l) {
		mDownloadFinishListener = l;
	}
	
	public void setOnBitmapDownloadFinishListener(OnBitmapDownFinishListener l) {
		mBitmapDownloadFinishListenr = l;
	}
	
	@Override
	protected Boolean doInBackground(String... arg0) {
		boolean ret = false;
		if(mIsCacheDownload) {
			BKLog.i("startDownloadTask for " + filename);
			BKLog.i("url : " + url + ", filename : " + filename);
			ret = downloadBitmap(url, filename);
			
			if(mDownloadFinishListener != null) {
				mDownloadFinishListener.onDownloadFinished(ret, url);
			}
		} else {
			BKLog.i("bitmap download task start");
			mBitmapResultArray = new ArrayList<Bitmap>();
			if(mBitmapUrlArray.size() > 0) {
				BKLog.i("Bitmap array count : " + mBitmapUrlArray.size());
				for(int i = 0; i < mBitmapUrlArray.size(); i++) {
					BKLog.e(i + " bitmap download ----------------------------------------" + mBitmapUrlArray.get(i));
					Bitmap img = downloadBitmap(mBitmapUrlArray.get(i));
					BKLog.i("--");
					mBitmapResultArray.add(img);
					if(img != null) {
						BKLog.i("width : " + img.getWidth() + ", height : " + img.getHeight());
						int max = CommonUtils.getGreatestCommonMeasure(img.getWidth(), img.getHeight());
						
						int x = img.getWidth() / max;
						int y = img.getHeight() / max;
						
						BKLog.i(x + ":" + y + " image.");
						BKLog.i(i + " bitmap put in array complete");
					}
				}
				ret = true;
			} else {
				ret = false;
			}
		}
		
		return ret;
	}
	
	/*
	 * web server로 부터 image을 다운로드 한다. 다운로드된 파일은 로컬 경로에 저장한다.
	 * @param	[IN] url: 다운로드 받을 URL
	 * 			[IN]filename: 다운로드 받은 데이타를 저장할 파일 이름
	 * @return	true: 성공, false: 실패
	 */
	private boolean downloadBitmap(String url, String filename) {
		
		final HttpClient client = new DefaultHttpClient();
	    final HttpGet getRequest = new HttpGet(url);
	    try 
	    {
	        HttpResponse response = client.execute(getRequest);
	        final int statusCode = response.getStatusLine().getStatusCode();
	        
	        if (statusCode != HttpStatus.SC_OK) 
	        {
	            return false;
	        }

	        final HttpEntity entity = response.getEntity();
	        if (entity != null) 
	        {
	            InputStream inputStream = null;
	         
	            try {
	            	inputStream = entity.getContent();
	            	
	            	// 다운로드 받은 데이타를 파일로 저장하기
	            	byte[] buffer = new byte[BUFFER_SIZE];
	            	String filePath = mCachePath + filename;
	            	FileOutputStream fos = new FileOutputStream(filePath);
	            	BufferedInputStream bis = new BufferedInputStream(inputStream, BUFFER_SIZE);
	        		BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
	        		int byteCnt=0;
	        		while((byteCnt = bis.read(buffer)) != -1){
	        			bos.write(buffer,0,byteCnt);
	        		}
	        		bis.close();
	        		inputStream.close();
	        		bos.flush();
	        		bos.close();
	        		fos.flush();
	        		fos.close();
	            	return true;
	            } catch (Exception e) {
					return false;
				} finally {
	                if (inputStream != null) 
	                {
	                    inputStream.close();
	                }
	                
	                entity.consumeContent();
	                return true;
	            }
	        }
	    } 
	    catch (IOException e) 
	    {
	        getRequest.abort();
	    } 
	    catch (IllegalStateException e) 
	    {
	        getRequest.abort();		    
	    } 
	    
	    
	    catch (Exception e) 
	    {
	        getRequest.abort();
	    } 
	    finally 
	    {
	        if ((client instanceof AndroidHttpClient)) 
	        {
	            ((AndroidHttpClient)client).close();
	        }
	    }
		
		return false;
	}
	
	private Bitmap downloadBitmap(String src) {
		try {
	        java.net.URL url = new java.net.URL(src);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setReadTimeout(500);
	        connection.setDoInput(true);
	        connection.connect();
	        InputStream input = connection.getInputStream();
	        Bitmap myBitmap = BitmapFactory.decodeStream(input);
	        return myBitmap;
	    } catch (IOException e) {
	        e.printStackTrace();
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return null;
	}
	
	/*
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 * @param	[IN] result: 이미지 다운로드 성공 여부(true: 성공, false: 실패)
	 */
	protected void onPostExecute(Boolean result) {
		BKLog.i("finish Download Task for " + filename);
		if(isCancelled()) {
			
		}
		if(mIsCacheDownload) {
			if (buttonReference != null) {
				BKLog.i("Button reference not null!!");
				
				ImageButton button = buttonReference.get();
				
				if(result == true) {
					Bitmap bitmap = BKImageDownloaderTask.getBitmap(mCachePath + filename);
					button.setBackgroundDrawable(new BitmapDrawable(bitmap));
					
					/* ###### Ben, Temp code */
					if(mIsShowDirectly) {
						button.setVisibility(View.VISIBLE);
						BKLog.d("Button visible");
					}
					
				} else { /*####### Ben ######## 다운로드실패시 기본 이미지 지정*/
//						imageView.setBackgroundResource(null);
				}
					
			} else {
				BKLog.e("Button reference null!!");
			}
		} else {
			BKLog.e("------------------------------Bitmap download finished");
			if(mBitmapDownloadFinishListenr != null) {
				mBitmapDownloadFinishListenr.onBitmapDownloadFinished(true, mBitmapResultArray);
			}
		}
		
		
	}
	
	/*
	 * load downloaded image
	 * @param	path: path for image
	 * @return	bitmap
	 */
	public static Bitmap getBitmap(String path) {
//		BKLog.i"chche fileName : " + path);
		Bitmap bitmap = null;
		InputStream is = null;
		try {
			is = new FileInputStream(path);
			bitmap = BitmapFactory.decodeStream(is);
			try {
				is.close();
				is = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
}
